{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 超参数(在运行kNN算法之前传入的参数)\n",
    "\n",
    "+ 超参数：在算法运行前需要决定的参数\n",
    "+ 模型参数：算法过程中学习的参数\n",
    "\n",
    "> kNN算法没有模型参数，kNN算法中的k是典型的参数\n",
    "\n",
    "如何寻找号的超参数：\n",
    "+ 领域知识\n",
    "+ 经验数值\n",
    "+ 实验搜索"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn import datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "digits = datasets.load_digits() # 数字识别算法集，结果只有0~9\n",
    "X = digits.data\n",
    "y = digits.target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9916666666666667"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "knn_clf = KNeighborsClassifier(n_neighbors=3)\n",
    "knn_clf.fit(X_train, y_train)\n",
    "knn_clf.score(X_test, y_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 寻找最好的k"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "# 最好的分数，不断寻找最好的k来得到最高的score记录入best_score\n",
    "best_score = 0.0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "# 临近点最好的k\n",
    "best_k = -1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "best_k =  3\n",
      "best_score =  0.991666666667\n"
     ]
    }
   ],
   "source": [
    "# for循环去找合适的参数(后面会看到sklearn提供了现成的方法来直接拿到最好的参数值)\n",
    "for k in range(1, 11):\n",
    "    knn_clf = KNeighborsClassifier(n_neighbors=k)\n",
    "    knn_clf.fit(X_train, y_train)\n",
    "    score = knn_clf.score(X_test, y_test)\n",
    "    if score > best_score:\n",
    "        best_k = k\n",
    "        best_score = score\n",
    "        \n",
    "print(\"best_k = \", best_k)\n",
    "print(\"best_score = \", best_score) # 如果过大或者过小就应该适当扩大k的范围"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 另一个超参数：距离的权重\n",
    "> k近邻算法的权重参数的含义,类似加权图中的边的权重值\n",
    "![k近邻算法的权重参数的含义](images/k近邻算法的权重参数的含义.jpg)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "best_method = uniform\n",
      "best_k =  3\n",
      "best_score =  0.991666666667\n"
     ]
    }
   ],
   "source": [
    "best_method = \"\"\n",
    "best_score = 0.0\n",
    "best_k = -1\n",
    "for method in [\"uniform\", \"distance\"]: # 距离的权重\n",
    "    for k in range(1, 11): # 取地临近点的个数\n",
    "        knn_clf = KNeighborsClassifier(n_neighbors=k, weights=method)\n",
    "        knn_clf.fit(X_train, y_train)\n",
    "        score = knn_clf.score(X_test, y_test)\n",
    "        if score > best_score:\n",
    "            best_method = method\n",
    "            best_k = k\n",
    "            best_score = score\n",
    "print(\"best_method = \"+best_method)        \n",
    "print(\"best_k = \", best_k)\n",
    "print(\"best_score = \", best_score) # 如果过大或者过小就应该适当扩大k的范围"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 另一个超参数：距离的权重\n",
    "\n",
    "> 曼哈顿距离和欧拉距离的通用性提取---->明科夫斯基距离\n",
    "![明科夫斯基距离1](images/明科夫斯基距离1.jpg)\n",
    "\n",
    "> 曼哈顿距离和欧拉距离的通用性提取---->明科夫斯基距离\n",
    "![明科夫斯基距离2](images/明科夫斯基距离2.jpg)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "best_p =  2\n",
      "best_k =  3\n",
      "best_score =  0.991666666667\n",
      "CPU times: user 20.4 s, sys: 352 ms, total: 20.8 s\n",
      "Wall time: 22.6 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "best_p = \"\" # 明科夫斯基的最佳参数\n",
    "best_score = 0.0\n",
    "best_k = -1\n",
    "for k in range(1, 11):\n",
    "    for p in range(1, 6):\n",
    "        knn_clf = KNeighborsClassifier(n_neighbors=k, weights=\"distance\",p=p)\n",
    "        knn_clf.fit(X_train, y_train)\n",
    "        score = knn_clf.score(X_test, y_test)\n",
    "        if score > best_score:\n",
    "            best_p = p\n",
    "            best_k = k\n",
    "            best_score = score\n",
    "print(\"best_p = \", best_p)        \n",
    "print(\"best_k = \", best_k)\n",
    "print(\"best_score = \", best_score) # 如果过大或者过小就应该适当扩大k的范围"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
